# -- coding: utf-8 --
# @time : 2023/5/3
# @author : 周梦泽
# @file : __init__.py
# @software: pycharm

from dataclasses import dataclass
from typing import Union

import pandas as pd
from pandas import DataFrame

from autoTask.taobao.redis_key_mange import RedisKey
from common.redis import redis_client
from common.utils import StrUtil, ObjUtil, DateUtil
from common.logger.log import log_

# 获取 key 前缀
xgfx_key_prefix = RedisKey.sycm.xgfx.key
ssph_key_prefix = RedisKey.sycm.ssph.key


@dataclass
class CacheTable:
    search_content: str
    data_word: str
    date_cycle: int
    table_topic_list: list

    def build_key(self, key_type: str):
        """
        构造 key
        :return:
        """
        key_prefix = {"xgfx": xgfx_key_prefix, "ssph": ssph_key_prefix}
        # arg_list = (self.search_content, self.data_word, self.dateCycle, self.hot_term_day)
        arg_list = (self.search_content, self.data_word, self.date_cycle)
        all_not_blank = all([v != '' for v in arg_list])
        if key_type in key_prefix:
            if all_not_blank:
                if not self.table_topic_list:
                    return key_prefix[
                        key_type] + f"{self.search_content}:{self.data_word}:{self.date_cycle}"
                else:
                    table_topic_key = ':'.join(self.table_topic_list)
                    return key_prefix[
                        key_type] + f"{self.search_content}:{self.data_word}:{self.date_cycle}:{table_topic_key}"

            else:
                return None
        else:
            raise Exception("key值错误")

    def set_cache(self, key_type: str, value: str, export: int):
        # print(value)
        # print(type(value))
        if ObjUtil.is_empty(value):
            log_.warning(
                f"设置缓存时值为空 : 品类: {self.search_content}, 目标词类 :{self.data_word}, 搜索排行页面的数据周期:{self.date_cycle}, "
                f"相关分析页面的数据周期:{self.date_cycle}")
            return
        key = self.build_key(key_type)
        if key is None:
            log_.warning(
                f"设置缓存时构造key失败 : 品类: {self.search_content}, 目标词类 :{self.data_word}, 搜索排行页面的数据周期:{self.date_cycle}")
            return
        redis_client.put(key=key, value=value, ex=export)

    def get_cache(self, key_type) -> [None, str]:
        key = self.build_key(key_type)
        if key is None:
            log_.warning(f"获取缓存时构造key失败 : 品类: {self.search_content}, 目标词类 :{self.data_word}, \
            搜索排行页面的数据周期:{self.date_cycle}")
            return None
        result = redis_client.get(key=key, type_=str)
        if ObjUtil.is_empty(result):
            return None
        return result

    def put_cache_by_df(self, key_type: str, df: DataFrame, ex: int = DateUtil.seconds_until_end_of_day(1)):
        """
        通过解析好的 DataFrame 添加缓存
        :param key_type: str
        :param df: 页面的 csv 解析后的数据
        :param ex: 过期时间 默认当前时间到今天结束的时间距离 秒数
        :return:
        """
        key = self.build_key(key_type)
        data_list = df.values.tolist()
        header_list = df.columns.tolist()
        result_list = data_list + [header_list]
        for index, item in enumerate(result_list):
            redis_client.h_set_put(key, index, item, ex=ex)

    def get_search_key_df(self, key_type: str) -> Union[pd.DataFrame, None]:
        """
        获取搜索词的结果列表
        :param key_type: 搜索用的关键词
        :return:这个搜索词列表
        """
        dict_list = redis_client.h_set_get(self.build_key(key_type), key_type=str, value_type=list)
        result = []
        for item in dict_list:
            result.extend(item.values())

        if result:
            for index, sub_list in enumerate(result):
                if '日期' in sub_list:
                    col_names = result[index]
                    result.pop(index)
                    df = pd.DataFrame(result, columns=col_names)
                    return df
        else:
            return None
